﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using METU_CMT.Business;

namespace METU_CMT
{
    public partial class InstructorLectureNotesMainScreen : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                BindLectureNotes();
            }
        }

        protected void OnBtnAddClicked(object sender, EventArgs e)
        {
            StringBuilder _dosyaAdi = new StringBuilder();
            DateTime _now = DateTime.Now;

            if (string.IsNullOrEmpty(fuNewSchedule.FileName))
            {
                //ShowAlert("Lütfen eklemek istediğiniz dosyayı seçiniz...");
                return;
            }
            HttpPostedFile _myFile = fuNewSchedule.PostedFile;
            string _fileExt = Path.GetExtension(fuNewSchedule.FileName);

            if (string.IsNullOrEmpty(_fileExt))
            {
                //ShowAlert("Yüklemek istediğiniz dosyanın uzantısı bulunamadı.");
                return;
            }

            if (_myFile.ContentLength > 10500000)
            {
                //ShowAlert("Yükleyeceğiniz dosyanın boyutu 10 MB sınırını geçmemelidir.");
                return;
            }
            if (!_fileExt.ToLower().Equals(".doc") && !_fileExt.ToLower().Equals(".docx") &&
                !_fileExt.ToLower().Equals(".txt") && !_fileExt.ToLower().Equals(".xls") &&
                !_fileExt.ToLower().Equals(".xlsx") && !_fileExt.ToLower().Equals(".pdf") &&
                !_fileExt.ToLower().Equals(".ppt") && !_fileExt.ToLower().Equals(".pptx") &&
                !_fileExt.ToLower().Equals(".jpg") && !_fileExt.ToLower().Equals(".bmp") &&
                !_fileExt.ToLower().Equals(".png") && !_fileExt.ToLower().Equals(".rtf") &&
                !_fileExt.ToLower().Equals(".jpeg"))
            {
                //ShowAlert(
                //    "Yalnızca Word, Excel, PowerPoint, PDF, Resim ve Video tipinde dosyalar yükleyebilirsiniz.");
                return;
            }
            if (_dosyaAdi.ToString().Contains("$"))
            {
                //TODO: Log: file name cannot contain $
                return;
            }

            _dosyaAdi.Append(
                Path.GetFileNameWithoutExtension(fuNewSchedule.FileName));
            _dosyaAdi.Append("$" + EntityFactory.User.UserId + "_");
            _dosyaAdi.Append(_now.ToString("yyyyMMddhhmmss"));
            StringBuilder _savePath =
                new StringBuilder(Server.MapPath("~/LectureNotes/") + _dosyaAdi + _fileExt);

            fuNewSchedule.PostedFile.SaveAs(_savePath.ToString());

            fuNewSchedule.Dispose();

            CourseInstructor _currentCourse = (CourseInstructor)EntityFactory.GetCurrentCourse(UserType.Instructor);
            Note _note = new Note {File = _dosyaAdi + _fileExt, Name = fuNewSchedule.FileName, UploadTime = _now};
            _currentCourse.AddNote(_note);

            NotifyUsers(fuNewSchedule.FileName);

            BindLectureNotes();
        }

        private void NotifyUsers(string _lectureNoteName)
        {
            CourseInstructor _currentCourse = (CourseInstructor)EntityFactory.GetCurrentCourse(UserType.Instructor);

            string _body = "<b>Course Name: </b>" + _currentCourse.CourseName + "<br/><b>Lecture Note Name: </b>" +
                           _lectureNoteName;
            string _mailSubject = "New Lecture Note is added!";

            List<Student> _students = _currentCourse.Students;
            string _mailAdresses = string.Empty;

            foreach (var _student in _students)
            {
                if (!string.IsNullOrEmpty(_student.Email) && _student.Email.Contains("@"))
                {
                    _mailAdresses += _student.Email + ";";
                }
            }

            Email _email = new Email(_mailSubject, _body, _mailAdresses);
            _email.SendEmail();
        }

        private void BindLectureNotes()
        {
            CourseInstructor _currentCourse = (CourseInstructor)EntityFactory.GetCurrentCourse(UserType.Instructor);
            dtgLectureNotes.DataSource = _currentCourse.LectureNotes;
            dtgLectureNotes.DataBind();
        }

        protected void OnLnkBtnNoteNameClicked(object sender, EventArgs e)
        {
            int _noteId = CommonMethods.GetIdFromGridViewRow((GridViewRow) ((LinkButton) (sender)).NamingContainer);
            CourseInstructor _currentCourse = (CourseInstructor)EntityFactory.GetCurrentCourse(UserType.Instructor);
            _currentCourse.LectureNotes.Find(note => note.NoteId == _noteId).Download();
        }

        protected void OnDtgLectureNotesRowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int _noteId = CommonMethods.GetIdFromGridViewRow(dtgLectureNotes.Rows[e.RowIndex]);
            CourseInstructor _currentCourse = (CourseInstructor)EntityFactory.GetCurrentCourse(UserType.Instructor);
            _currentCourse.DeleteNote(_noteId);

            BindLectureNotes();
        }
    }
}